console.log('Happy developing ✨')
const emq = require('mqtt');
const StringDecoder = require('string_decoder').StringDecoder;
const qos = 0;
const opts = { qos};
const souUrl ='tcp://10.8.5.54:10049';
const distUrl ='tcp:/10.13.60.134:1883';
run()
function run(){
    try{
        souClient = emq.connect(souUrl, opts);
        souClient.on('connect', packet => {
            console.log("connect ok ",souUrl)
            var topics = [
                '+/databack',
            ];
            topics.forEach(topic => {
                const qos = 0
                souClient.subscribe(topic, { qos }, (error) => {
                    if (error) {
                        console.log('subscribe error:', error)
                        return
                    }
                    console.log(`Subscribe to topic '${topic}'`)
                })
            })

            souClient.on('message', async (topic, message) => {

                const payload = buffer2str(message);
                console.log("源收到MQTT消息",topic, payload);
                const opt = {qos: 0, retain: false};
                distClient.publish(topic, payload, opt, err => {
                    console.log(err)
                    if (err) {
                        console.log('mqtt pub error', topic, err);
                    }
                });
            });

            souClient.on('error', error => {
                console.log(error, url);
            });
            souClient.on('close', error => {
            });

            souClient.on('offline', error => {
            });
            //  return Promise.resolve('');
        });
    }
    catch(err){
        console.error(err.stack);
    }

}
function runDist(){
    distClient = emq.connect(distUrl, opts);
    distClient.on('connect', packet => {
        console.log("connect ok ",distUrl)
        var topics = [
            '+/databack',
        ];
        topics.forEach(topic => {
            const qos = 0
            souClient.subscribe(topic, { qos }, (error) => {
                if (error) {
                    console.log('dist subscribe error:', error)
                    return
                }
                console.log(`dist Subscribe to topic '${topic}'`)
            })
        })

        distClient.on('message', async (topic, message) => {
            console.log(topic, "dist",message);
        });

        distClient.on('error', error => {
            console.log(error, url);
        });
        distClient.on('close', error => {
        });

        distClient.on('offline', error => {
        });
        //  return Promise.resolve('');
    });


    distClient.on('message', async (topic, message) => {
        console.log(topic, "dist",message);
    });
}

function buffer2str(buffer) {
    try {
        const decoder = new StringDecoder('utf8');
      return decoder.write(buffer);

    } catch (e) {
        return undefined;
    }
}
